package com.yipinhouse.employee.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yipinhouse.common.exception.HouseException;
import com.yipinhouse.common.exception.HouseException;
import com.yipinhouse.common.result.Result;
import com.yipinhouse.employee.common.EmployeeResultCode;
import com.yipinhouse.employee.common.enums.HouseStatusEnum;
import com.yipinhouse.employee.common.enums.HouseTypeEnum;
import com.yipinhouse.employee.common.utils.HttpUtils;
import com.yipinhouse.employee.infra.mapper.BrokerInfoMapper;
import com.yipinhouse.employee.infra.model.BrokerInfo;
import com.yipinhouse.employee.service.BrokerInfoService;
import com.yipinhouse.employee.service.dto.BrokerInfoDto;
import com.yipinhouse.employee.service.dto.ShopBrokerInfoDto;
import com.yipinhouse.employee.service.dto.PromotionDto;
import com.yipinhouse.employee.service.param.AddBrokerServiceParam;
import com.yipinhouse.employee.service.param.LoginServiceParam;
import com.yipinhouse.house.client.*;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 经纪人信息表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-11-30
 */
@Service
public class BrokerInfoServiceImpl extends ServiceImpl<BrokerInfoMapper, BrokerInfo> implements BrokerInfoService {

    @Resource
    private NewHouseQueryClient newHouseQueryClient;

    @Resource
    private ResoldApartmentQueryClient resoldApartmentQueryClient;

    @Resource
    private ResoldHouseQueryClient resoldHouseQueryClient;

    @Resource
    private ResoldApartmentManageClient resoldApartmentManageClient;

    @Resource
    private ResoldHouseManageClient resoldHouseManageClient;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private BrokerInfoMapper brokerInfoMapper;

    /**
     * 添加员工
     *
     * @param addBrokerServiceParam
     * @return
     */
    @Override
    public BrokerInfoDto addBroker(AddBrokerServiceParam addBrokerServiceParam) {
        if (addBrokerServiceParam.getPhone().length() != 11) {
            throw new HouseException("手机号码不正确", 5001);
        }
        JSONObject certification = certification(addBrokerServiceParam.getIdCar(), addBrokerServiceParam.getRealName());
        if (certification.isEmpty() || certification.size() < 1 || certification == null) {
            throw new HouseException("身份证与姓名不匹配", 5002);
        }
        if (!addBrokerServiceParam.getGander().equals("W") && !addBrokerServiceParam.getGander().equals("M")) {
            throw new HouseException("性别错误，W为女，M为男", 5003);
        }
        String sex = certification.get("sex").toString();
        if (sex.equals("男")) {
            sex = "M";
        } else {
            sex = "W";
        }
        if (!addBrokerServiceParam.getGander().equals(sex)) {
            throw new HouseException("身份证与性别不匹配", 5004);
        }
        if (addBrokerServiceParam.getBankCard().length() != 19 && addBrokerServiceParam.getBankCard().length() != 17) {
            throw new HouseException("工资卡号位数不满足19或17位", 5005);
        }

        BrokerInfo brokerInfo = new BrokerInfo();
        //默认手机号为账号
        brokerInfo.setAccount(addBrokerServiceParam.getPhone());
        //密码默认123456
        brokerInfo.setPassword("123456");
        brokerInfo.setPhone(addBrokerServiceParam.getPhone());
        brokerInfo.setGander(addBrokerServiceParam.getGander());
        brokerInfo.setIdCar(addBrokerServiceParam.getIdCar());
        brokerInfo.setBankCard(addBrokerServiceParam.getBankCard());
        brokerInfo.setRealName(addBrokerServiceParam.getRealName());
        brokerInfo.setWorkNumber(addBrokerServiceParam.getWorkNumber());
        //只能添加普通员工
        brokerInfo.setPosition("STAFF");
        save(brokerInfo);
        return BeanUtil.copyProperties(brokerInfo, BrokerInfoDto.class);
    }

    /**
     * 员工登录信息验证
     *
     * @param loginServiceParam
     * @return
     */
    @Override
    public Integer login(LoginServiceParam loginServiceParam) {
        BrokerInfo brokerInfo = getOne(new QueryWrapper<BrokerInfo>()
                .eq("account", loginServiceParam.getAccount()));
        if (brokerInfo == null) {
            throw new HouseException("账号不存在", 5007);
        }
        if (!brokerInfo.getPassword().equals(loginServiceParam.getPassword())) {
            throw new HouseException("密码错误", 5008);
        }
        return brokerInfo.getId();
    }

    /**
     * 查询员工个人信息
     *
     * @param brokerId
     * @return
     */
    @Override
    public BrokerInfoDto getBrokerInfo(Integer brokerId) {
        BrokerInfo broker = getById(brokerId);
        if (broker == null) throw new HouseException("员工不存在", 5009);
        BrokerInfoDto brokerInfoDto = BeanUtil.copyProperties(broker, BrokerInfoDto.class);
        return brokerInfoDto;
    }

    @Override
    public void orderHouse(Integer houseId, String houseType, Integer brokerId) {
//        判断房源状态是否可以预定
        String houseStatus = "";
        Result statusResult = null;

        //        创建分布式锁
        RLock rLock = redissonClient.getLock("signing:" + houseType + ":houseId:" + houseId);

        boolean flag = false;

        try {
            flag = rLock.tryLock(20, 20, TimeUnit.SECONDS);
            if (flag) {
                //获取房源状态
                if (houseType.equals(HouseTypeEnum.NEW.getCode()))
                    statusResult = newHouseQueryClient.checkHouseStatus(houseId);
                else if (houseType.equals(HouseTypeEnum.RENT.getCode()))
                    statusResult = resoldHouseQueryClient.checkHouseStatus(houseId);
                else if (houseType.equals(HouseTypeEnum.RESOLD.getCode()))
                    statusResult = resoldApartmentQueryClient.checkHouseStatus(houseId);

                if (statusResult == null || (!statusResult.isSuccess()))
                    throw new HouseException("分表查询错误", 600);

                //TODO 更改新房的房源状态字段
                houseStatus = String.valueOf(statusResult.getData());
                if (!(houseStatus.equals(HouseStatusEnum.SALE.getCode()) || houseStatus.equals(HouseStatusEnum.ORDERED.getCode())))
                    throw new HouseException(EmployeeResultCode.HOUSE_CAN_NOT_ORDER);

                //        开始预定房源
                Result orderResult = null;
                if (houseType.equals(HouseTypeEnum.NEW.getCode()))
                    orderResult = newHouseQueryClient.orderHouse(houseId);
                else if (houseType.equals(HouseTypeEnum.RENT.getCode()))
                    orderResult = resoldHouseManageClient.orderHouse(houseId);
                else if (houseType.equals(HouseTypeEnum.RESOLD.getCode()))
                    orderResult = resoldApartmentManageClient.orderHouse(houseId);

                if (orderResult == null || (!orderResult.isSuccess()))
                    throw new HouseException(EmployeeResultCode.HOUSE_ORDER_FAILED);

            } else
                throw new HouseException(EmployeeResultCode.LOCK_FAILED);

        } catch (InterruptedException e) {
            throw new HouseException(EmployeeResultCode.LOCK_FAILED);
        } finally {
            if (rLock != null)
                rLock.unlock();
        }


    }

    /**
     * 关联员工与门店
     *
     * @param shopId
     * @param brokerId
     */
    @Override
    public boolean correlation(Integer shopId, Integer brokerId) {
        BrokerInfo brokerInfo = getById(brokerId);
        if (brokerInfo == null) {
            throw new HouseException("员工不存在", 5009);
        }
        brokerInfo.setShopId(shopId);
        updateById(brokerInfo);
        return true;
    }

    /**
     * 升职，获取员工信息，修改员工职位
     *
     * @param brokerId
     * @return
     */
    @Override
    public PromotionDto promotion(Integer brokerId, Integer shopId) {
        BrokerInfo brokerInfo = getById(brokerId);
        if (brokerInfo == null) {
            throw new HouseException("员工不存在", 5009);
        }
        if (brokerInfo.getShopId() != shopId) {
            throw new HouseException("该员工不属于该门店", 5010);
        }
        if (!brokerInfo.getPosition().equals("STAFF")) {
            throw new HouseException("该员工不满足升职职位要求", 5011);
        }
        PromotionDto promotionDto = new PromotionDto();
        promotionDto.setBrokerId(brokerInfo.getId());
        promotionDto.setPhone(brokerInfo.getPhone());
        promotionDto.setNegozianteName(brokerInfo.getRealName());
        //修改员工职位为店长
        brokerInfo.setPosition("SHOPOWNER");
        updateById(brokerInfo);
        return promotionDto;
    }

    /**
     * 查询门店员工
     * @param shopId
     * @return
     */
    @Override
    public List<ShopBrokerInfoDto> getBrokerByShopId(Integer shopId) {
        List<BrokerInfo> brokerInfos = brokerInfoMapper.selectList(new QueryWrapper<BrokerInfo>().eq("shop_id", shopId));
        if (brokerInfos == null||brokerInfos.size()<=0) throw new HouseException("门店暂无员工",5001);
        List<ShopBrokerInfoDto> brokerInfoDtos = BeanUtil.copyToList(brokerInfos, ShopBrokerInfoDto.class);
        return brokerInfoDtos;
    }

    /**
     * 调取api验证身份信息
     *
     * @param idCard
     * @param realname
     * @return
     */
    public JSONObject certification(String idCard, String realname) {
        String host = "https://jmrnhappy.market.alicloudapi.com";
        String path = "/idcard/validate";
        String method = "POST";
        String appcode = "ca0cfcbc58eb489cab2971fa1f26bcf6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        //身份证号码
        bodys.put("idCardNo", idCard);
        //真实姓名
        bodys.put("name", realname);
        try {

            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            System.out.println("================================================");
            //获取response的body
            String s = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject object = JSONObject.parseObject(s);
            System.out.println(s);
            System.out.println("================================================");
            Object data = object.get("data");
            System.out.println(data);
            JSONObject object2 = JSONObject.parseObject(data.toString());
            return object2;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
